#include "cardwordlist.h"

CardWordList::CardWordList( DbLink* pcDbLink, wxString& cardTableName, wxString& soundFileDir )
: CardWordDialog( NULL ), BaseList( m_listCtrl, soundFileDir )
{
	m_pcDbLink = pcDbLink;
	m_pDictDb  = pcDbLink->GetDictDb();
	m_pCardDb  = pcDbLink->GetCardDb();
	
	m_sCardTableName = cardTableName;
	
	m_lItemIdx = -1;
	m_lWordNum = -1;
	
	m_listCtrl->InsertColumn( eWordList_Id,        _("Id"),          wxLIST_FORMAT_LEFT, 0 );
	m_listCtrl->InsertColumn( eWordList_TableName, _("Table name"),  wxLIST_FORMAT_LEFT, 0 );
	m_listCtrl->InsertColumn( eWordList_Word,      _("Word"),        wxLIST_FORMAT_LEFT, 180 );
	m_listCtrl->InsertColumn( eWordList_Tran,      _("Translation"), wxLIST_FORMAT_LEFT, 410 );	
	m_listCtrl->InsertColumn( eWordList_Score,     _("Score"),       wxLIST_FORMAT_LEFT, 50 );

	m_buttonOk->SetFocus();
}

CardWordList::~CardWordList()
{
}

void CardWordList::OnEnterWindow( wxMouseEvent& event )
{
	m_listCtrl->SetFocus();
}
	
void CardWordList::ClearInfo()
{
	m_sScore.Clear();
	SetScore( m_sScore );

	m_buttonPlay->Enable( false );
}

void CardWordList::SetInfo()
{
	m_lItemIdx = m_listCtrl->GetNextItem( -1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED );

	m_sWordId = GetColumnText( eWordList_Id );	
	m_sDictTableName = GetColumnText( eWordList_TableName );
	m_sScore = GetColumnText( eWordList_Score );

	SetScore( m_sScore );

	m_buttonPlay->Enable( true );
}

long CardWordList::FillList( bool bClear )
{
	// clear list
	if( bClear )
	{		
		ClearInfo();	
		m_pcListCtrl->DeleteAllItems();
	}
		
	// get list of tables in the db
	wxSQLite3ResultSet cWordSet = m_pCardDb->ExecuteQuery( wxT( "SELECT * FROM " ) + m_sCardTableName );
	long lCount = 0;
	
	// fill the list
	while( cWordSet.NextRow() )
	{			
		// get card info
		wxString sId = cWordSet.GetAsString(0);
		wxString sDictTableName = cWordSet.GetAsString(1);
		wxString sScore = cWordSet.GetAsString(2);
		
		// get word and translation
		wxString sQuery = wxT("SELECT word, tran FROM ") + sDictTableName + wxT(" WHERE id = ") + sId;
		wxSQLite3ResultSet cResultSet = m_pDictDb->ExecuteQuery( sQuery );
		wxString sWord = cResultSet.GetAsString(0);
		wxString sTran = cResultSet.GetAsString(1);
		cResultSet.Finalize();
			
		wxString s[eWordList_Cols];
		
		s[eWordList_Id] = sId;
		s[eWordList_TableName] = sDictTableName;
		s[eWordList_Word] = sWord;
		s[eWordList_Tran] = sTran;
		s[eWordList_Score] = sScore;
		
		InsertItem( s, eWordList_Cols );
		
		lCount++;
	}
	cWordSet.Finalize();
	
	return lCount;
}

void CardWordList::OnWordDeselected( wxListEvent& WXUNUSED( event ) )
{	
	if( m_listSelectedItems.size() )
	{
		std::list<long>::iterator it = m_listSelectedItems.begin();
		long idx = *it;
		m_listSelectedItems.erase( it );
		m_listCtrl->DeleteItem( idx );
	}

	// reduce number of selected items
	m_lItemNum--;

	if( m_lItemNum == 1 )
		SetInfo();
	else
		ClearInfo();

	if( m_lItemNum == 0 )
		m_buttonDelete->Enable( false );
}

void CardWordList::OnWordSelected( wxListEvent& WXUNUSED( event ) )
{	
	m_lItemIdx = -1;
	m_lItemIdx = m_listCtrl->GetNextItem( m_lItemIdx, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED );
		
	if( m_lItemIdx >= 0 )
	{			
		// increase number of selected items
		m_lItemNum++;

		m_buttonDelete->Enable( true );

		// allow to change info for single selected item
		if( m_lItemNum == 1 )
			SetInfo();
		else
			ClearInfo();
	}
}

void CardWordList::OnAddClick( wxCommandEvent& WXUNUSED( event ) )
{
	DictList cDict( m_pcDbLink, m_sSoundDir );
	cDict.Load();
	cDict.SetToggle();
	if( cDict.ShowModal() == wxID_OK )
	{
		wxString s[eWordList_Cols];
		s[eWordList_TableName] = cDict.GetTableName();
		
		if( s[eWordList_TableName].empty() )
			return;
			
		WordList cWord( s[eWordList_TableName], m_pDictDb, m_pCardDb, m_sSoundDir );
		cWord.Load();
		cWord.SetToggle();
		if( cWord.ShowModal() == wxID_OK )
		{
			while( cWord.GetWordInfo( s[eWordList_Id], s[eWordList_Word], s[eWordList_Tran] ) )
			{
				if( s[eWordList_Id].empty() || s[eWordList_Word].empty() || s[eWordList_Tran].empty() )
					return;
			
				s[eWordList_Score] = wxT("0");								
			
				// check the word in the card
				wxString sQuery = wxT("SELECT * FROM " ) + m_sCardTableName + wxT(" WHERE id = ") + s[eWordList_Id] + 
													wxT(" AND dicttable = '") + s[eWordList_TableName] + wxT("'");
												
				wxSQLite3ResultSet cResultSet = m_pCardDb->ExecuteQuery( sQuery );
				wxString sNum = cResultSet.GetAsString(0);
				cResultSet.Finalize();
			
				if( TableToLong( sNum, 0 ) )
				{
					wxMessageDialog( this, _("Word \"") + s[eWordList_Word] + _("\" already in the card"), _("Info"), wxOK | wxICON_INFORMATION ).ShowModal();
				}
				else
				{
					InsertItem( s, eWordList_Cols );
				
					wxString sQuery = wxT("INSERT INTO ") + m_sCardTableName + wxT(" VALUES (") +
													s[eWordList_Id] + wxT(", '") + s[eWordList_TableName] + wxT("', ") + s[eWordList_Score] + wxT(")");
			
					m_pCardDb->ExecuteUpdate( sQuery );				
				}
			}
		}
	}
}

void CardWordList::OnDeleteClick( wxCommandEvent& WXUNUSED( event ) )
{
	if( m_lItemIdx < 0 )
		return;

	m_lItemIdx = -1;

	while( ( m_lItemIdx = m_listCtrl->GetNextItem( m_lItemIdx, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED ) ) >= 0 )
	{
		// store selected items for further deletion
		m_listSelectedItems.push_back( m_lItemIdx );

		wxString wordId = GetColumnText( eWordList_Id );

		// delete word from the card db
		wxString sQuery = wxT("DELETE FROM ") + m_sCardTableName + wxT(" WHERE id = ") + wordId + wxT(" AND dicttable = '") +
											m_sDictTableName + wxT("'");
										
		m_pCardDb->ExecuteUpdate( sQuery );
	}
			
	// delete first item in the list, others will be deleted in deselected event
	std::list<long>::iterator it = m_listSelectedItems.begin();
	long idx = *it;
	m_listSelectedItems.erase( it );
	m_listCtrl->DeleteItem( idx );
}

void CardWordList::Load()
{
	m_lWordNum = FillList();
}

void CardWordList::OnPlayClick( wxCommandEvent& WXUNUSED( event ) )
{
	wxString file = GetFileName( m_sWordId ) ;
	PlayFile( file );
}

void CardWordList::OnOkClick( wxCommandEvent& WXUNUSED( event ) )
{
	wxString sScore = GetScore();
		
	if( sScore.empty() || sScore == m_sScore || m_sWordId.empty() )
	{
		if( IsModal() )
			EndModal( wxID_OK );
		return;
	}
		
	// update db entry
	if( sScore != m_sScore && !sScore.empty() && !m_sScore.empty() )
	{		
		wxString sQuery = wxT( "UPDATE " ) + m_sCardTableName + wxT( " SET score = ") + sScore + wxT(" WHERE id = ") + m_sWordId;
				
		m_pCardDb->ExecuteUpdate( sQuery );
		
		// uodate item text in the list
		UpdateItem();
	}
	else
		wxMessageDialog( NULL, wxT("Nothing to update"), wxT("Info"), wxOK | wxICON_INFORMATION ).ShowModal();
}

void CardWordList::UpdateItem()
{
	if( m_lItemIdx < 0 )
		return;
		
	m_sScore = GetScore();
	
	m_pcListCtrl->SetItem( m_lItemIdx, eWordList_Score, m_sScore );
}

void CardWordList::OnKeyDown( wxKeyEvent& event )
{
	if( event.GetKeyCode() == WXK_ESCAPE )
		OnCancelClick( (wxCommandEvent&) event );
	else
		event.Skip();
}